package org.example.sb_api.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.example.sb_api.common.Result;
import org.example.sb_api.dto.AppRecordDTO;
import org.example.sb_api.entity.App;
import org.example.sb_api.entity.DownloadRecord;
import org.example.sb_api.entity.Topic;
import org.example.sb_api.mapper.AppMapper;
import org.example.sb_api.mapper.DownloadRecordMapper;
import org.example.sb_api.mapper.TopicMapper;
import org.example.sb_api.service.AppService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
public class AppServiceImpl implements AppService {

    @Autowired
    private AppMapper appMapper;
    
    @Autowired
    private TopicMapper topicMapper;
    
    @Autowired
    private DownloadRecordMapper downloadRecordMapper;

    @Override
    public Result getAppList(Integer isRecommended, Integer isUpdated) {
        QueryWrapper<App> wrapper = new QueryWrapper<>();
        if (isRecommended != null) {
            wrapper.eq("is_recommended", isRecommended);
        }
        if (isUpdated != null) {
            wrapper.eq("is_updated", isUpdated);
        }
        
        List<App> apps = appMapper.selectList(wrapper);
        return Result.success(apps);
    }

    @Override
    public Result getTopicList() {
        List<Topic> topics = topicMapper.selectList(null);
        for (Topic topic : topics) {
            List<App> apps = appMapper.selectByTopicId(topic.getId());
            topic.setAppList(apps);
        }
        return Result.success(topics);
    }

    @Override
    public Result addDownloadRecord(AppRecordDTO recordDTO) {
        App app = appMapper.selectById(recordDTO.getAppId());
        if (app == null) {
            return Result.error("应用不存在");
        }
        
        // 更新下载次数
        app.setDownloadCount(app.getDownloadCount() + 1);
        appMapper.updateById(app);
        
        // 添加下载记录
        DownloadRecord record = new DownloadRecord();
        record.setAppId(recordDTO.getAppId());
        record.setUserId(recordDTO.getUserId());
        downloadRecordMapper.insert(record);
        
        return Result.success(null);
    }
} 